// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

var NetworkManager = require('NetworkManager')
var UnitTools = require('UnitTools')
var ClickManager = require('ClickManager')
var Config = require('Config')

var unionItem = cc.Class({
    name: 'unionItem',
    properties: {
        id: 0,
        username: cc.Label,
        headimg: cc.Sprite,
        rid: cc.Label,
        rname: cc.Label
    }
})

cc.Class({
    extends: cc.Component,

    properties: {
        token: null,
        unionItems: {
            default: [],
            type: unionItem
        },
        unionItemPrefab: cc.Prefab,
        unionItemsNode: cc.Node
    },

    // LIFE-CYCLE CALLBACKS:

    // active为true
    onEnable () {
        this.token = cc.sys.localStorage.getItem('__TOKEN__')
        this.getAllUnion()
    },

    start () {

    },

    // 获取全部联盟
    getAllUnion () {
        this.unionItemsNode.removeAllChildren()
        try {
            NetworkManager.onConnectedToHall( (hallService) => {
                hallService.proxy.getAllUnion(this.token, (data) => {
                    if (data.ok && data.code === 200) {
                        let list = JSON.parse(data.datas)

                        this.unionItemsNode.height = list.length
                        for (let i in list) {
                            if (list[i] !== null) {
                                let item = cc.instantiate(this.unionItemPrefab)
                                let user = list[i].user
                                let obj  = {
                                    id: list[i].rid,
                                    rid: list[i].rid,
                                    rname: list[i].name,
                                    headimg: Config.headPath + user.headimg,
                                    username: user.username
                                }

                                this.unionItemsNode.addChild(item)
                                item.getComponent('UnionItemList').init(obj)
                            }
                        }
                    }
                })
            })
        } catch (err) {
            cc.director.loadScene('loading')
        }
    }

    // update (dt) {},
});
